﻿using System;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using InvoiceChecking.Data;
using InvoiceChecking.Entities;

public partial class Admin_ExportPayment : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ddl_PaymentType.DataSource = DataRepository.PaymentTypeProvider.GetDistintCode();
            ddl_PaymentType.DataBind();
        }
    }

    protected void grv_BatchList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grv_PaymentList.PageIndex = e.NewPageIndex;
        BindData();
    }
    protected void btn_Filter_Click(object sender, EventArgs e)
    {
        BindData();
    }

    private void BindData()
    {
        string whereExpression = BuildWhereExpression();
        int count;
        VList<SunPaymentVoucher> vouchers = DataRepository.SunPaymentVoucherProvider.GetPaged(whereExpression, "VoucherNo", 0, 1000, out count);
        if (count == 0)
            lbl_Error.Text = "No data. Please check the filter expression";
        else
        {
            lbl_Error.Text = "";
        }
        grv_PaymentList.RecordsCount = count;
        grv_PaymentList.DataSource = vouchers;
        grv_PaymentList.DataBind();
    }

    private string BuildWhereExpression()
    {
        string whereExpression = "";
        if (!string.IsNullOrEmpty(tb_VoucherDateFrom.Text))
        {
            if (!string.IsNullOrEmpty(tb_VoucherDateTo.Text))
                whereExpression += string.Format("Transaction_dt BETWEEN '{0} 00:00:00' AND '{1} 23:59:59' AND TransType='{2}'", tb_VoucherDateFrom.Text,
                                                    tb_VoucherDateTo.Text, ddl_PaymentType.SelectedValue);
            else
                whereExpression += string.Format("DATEDIFF(d,Transaction_dt,'{0}') AND TransType='{1}'", tb_VoucherDateFrom.Text, ddl_PaymentType.SelectedValue);
        }
        return whereExpression;
    }
    protected void grv_BatchList_ExcelBeforeFormat(object sender, InvoiceChecking.Web.UI.ExcelFormatEventArgs e)
    {
        BindData();
    }

    protected void btn_Export_Click(object sender, EventArgs eventArgs)
    {
        ExportToExcel();
    }
    protected void ExportToExcel()
    {
        string authUserName = Context.User.Identity.Name.Split('\\')[1];
        string whereExpression = string.Format("PaymentId in (Select VoucherNo from SunPaymentVoucher Where Transaction_dt BETWEEN '{0} 00:00:00' AND '{1} 23:59:59' AND TransType='{2}')", tb_VoucherDateFrom.Text,
                                                tb_VoucherDateTo.Text, ddl_PaymentType.SelectedValue);
        int count;
        TList<Payment> exportList = DataRepository.PaymentProvider.GetPaged(whereExpression, "", 0, 10000, out count);
        foreach (var payment in exportList)
        {
            payment.ExportedDate = DateTime.Now;
            payment.ExportedBy = authUserName;
        }
        DataRepository.PaymentProvider.Update(exportList);
        //Response.Clear();
        //Response.AddHeader("content-disposition", "attachment;filename=SunPayment" + tb_VoucherDateFrom.Text + tb_VoucherDateTo.Text + ".xls");
        //Response.Charset = "";
        //Response.Cache.SetCacheability(HttpCacheability.NoCache);
        //Response.ContentType = "application/vnd.xls";
        //var stringWrite = new System.IO.StringWriter();
        //var htmlWrite = new HtmlTextWriter(stringWrite);
        //grv_PaymentList.RenderControl(htmlWrite);
        //string style = @"<style> .textmode { mso-number-format:\@; } </style>";
        //Response.Write(style);
        //Response.Output.Write(stringWrite.ToString());
        //lbl_Error.Text = stringWrite.ToString();
        //Response.End();
        Response.Clear();
        Response.Buffer = true;

        Response.AddHeader("content-disposition", "attachment;filename=SunPayment" + tb_VoucherDateFrom.Text + tb_VoucherDateTo.Text + ".xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);

        for (int i = 0; i < grv_PaymentList.Rows.Count; i++)
        {
            GridViewRow row = grv_PaymentList.Rows[i];

            //Apply text style to each Row
            for (int j = 0; j < row.Cells.Count; j++)
            {
                if (j > 7)
                    row.Cells[j].Attributes.Add("class", "textmode");
            }
        }
        grv_PaymentList.RenderControl(hw);
        //style to format numbers to string
        string style = @"<style> .textmode { mso-number-format:\@; } </style>";
        Response.Write(style);
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
           server control at run time. */
    }
    protected void ddl_PaymentType_SelectedIndexChanged(object sender, EventArgs e)
    {
        btn_Filter_Click(btn_Filter, null);
    }
}
